package com.zxb.base.auth;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zxb.core.common.R;
import com.zxb.core.common.User;
import com.zxb.core.dao.auth.AuthUser;
import com.zxb.core.dao.auth.AuthUserDao;
import com.zxb.core.util.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class TokenController {
    private final AuthUserDao userDao;

    @PostMapping("/un/token/create")
    public R casLogin(@RequestBody User u) {
        if (StrUtil.isBlank(u.getUsername())) {
            return R.error("用户名不能为空！");
        }
        if (StrUtil.isBlank(u.getPassword())) {
            return R.error("密码不能为空！");
        }
        AuthUser user = userDao.getOne(
                new LambdaQueryWrapper<AuthUser>()
                        .eq(AuthUser::getUsername, u.getUsername())
                        .eq(AuthUser::getPassword, u.getPassword()));
        if (user == null) {
            return R.error("用户名密码错误");
        }
        if(!user.getIsOpen()){
            return R.error("用户被禁用");
        }
        u.setId(user.getId());
        u.setName(user.getName());
        u.setIsOpen(user.getIsOpen());
        String token = TokenUtil.createToken(u);
        return R.success(token);
    }
}
